<script setup lang="ts">
import { ElForm, ElMessage } from 'element-plus';
import { onMounted, reactive, ref, toRefs, getCurrentInstance } from 'vue';
import { Search, Refresh, Message } from '@element-plus/icons-vue';
import { WithdrawalQuery, Withdrawal } from '@/api/system/withdrawal/types';
import {
  getWithdrawalList,
  withdrawalAdopt,
  withdrawalLose,
  exportReport,
  engineerStatistics,
} from '@/api/system/withdrawal';
import { Download } from '@element-plus/icons-vue';
import { object } from 'vue-types';
import EngineerOrderList from "@/views/statement/engineerOrderList.vue";
const { proxy }: any = getCurrentInstance();
const queryFormRef = ref(ElForm);
const formData = ref({
  cumulativeAmount: 0,
  totalAmount: 0,
  withdrawnAmount: 0,
  withdrawnAmountOnThis: 0,
  withdrawnAmountOnNo: 0
});
const refFrom = ref();
const engineerOrderListRef = ref();
const state = reactive({
  loading: true,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  } as any,
  hangrow: {} as any,
  bottomName: '',
  dialogFormVisible: false,
  remark: '',
  createTime: [] as string[],
  withdrawalList: [] as Withdrawal[],
  total: 0,
  dialog: {
    visible: false,
  } as DialogType,
});
const {
  loading,
  queryParams,
  createTime,
  withdrawalList,
  total,
  bottomName,
  dialogFormVisible,
  dialog,
  remark,
  hangrow,
} = toRefs(state);

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  console.log("queryParams.value", queryParams.value)
  if (createTime.value.length == 2) {
    queryParams.value.createTimeStart = proxy
      .$moment(createTime.value[0])
      .format('YYYY-MM-DD');
    queryParams.value.createTimeEnd = proxy
      .$moment(createTime.value[1])
      .format('YYYY-MM-DD');
  } else {
    queryParams.value.createTimeStart = undefined
    queryParams.value.createTimeEnd = undefined
  }
  queryParams.value.status = 1;
  getWithdrawalList(queryParams.value).then((res: any) => {
    withdrawalList.value = res.data.list;
    total.value = res.data.total;
    loading.value = false;
  });
}
/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  createTime.value = [];
  handleQuery();
}

/**
 * 查询提现金额
 */
function handleDetail(id: any) {
  engineerStatistics(id).then((res: any) => {
    Object.assign(formData.value, res.data);
  });
}

/**
 * 打开弹窗
 */
function openDialog(id: any) {
  dialog.value.visible = true;
  handleDetail(id);
}

/**
 * 关闭用户弹窗
 */
function closeDialog() {
  dialog.value.visible = false;
}

/**
 * 导出用户
 */
function handleExport() {
  exportReport(queryParams.value).then((response: any) => {
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    });
    const a = document.createElement('a');
    const href = window.URL.createObjectURL(blob); // 下载的链接
    a.href = href;
    a.download = decodeURI(
      response.headers['content-disposition'].split(';')[1].split('=')[1]
    ); // 获取后台设置的文件名称
    document.body.appendChild(a);
    a.click(); // 点击导出
    document.body.removeChild(a); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  });
}

onMounted(() => {
  handleQuery();
});

const approval = (row: any) => {
  withdrawalAdopt({
    id: row.id,
    money: row.money,
  }).then((res: any) => {
    if (res.code === '00000') {
      ElMessage.success(res.data);
    } else {
      ElMessage.error(res.data);
    }
    handleQuery();
  });
};
const bohui = () => {
  if (!state.remark) {
    ElMessage.error('请填写备注');
    return;
  }
  withdrawalLose({
    id: state.hangrow.id,
    money: state.hangrow.money,
    remark: state.remark,
  }).then((res: any) => {
    if (res.code === '00000') {
      ElMessage.success(res.data);
      state.dialogFormVisible = false;
    } else {
      ElMessage.error(res.data);
    }
    handleQuery();
  });
};
const turnDown = (row: any) => {
  state.dialogFormVisible = true;
  state.hangrow = row;
  state.bottomName = '驳回';
};
function getEngineerOrderList(row: any) {
  console.log("row", row.engineerId)
  engineerOrderListRef.value.open(row.engineerId);
}
</script>
<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">

        <el-form-item prop="engineerName" label="工程师姓名">
          <el-input v-model="queryParams.engineerName" placeholder="请输入工程师姓名" />
        </el-form-item>
        <el-form-item label="工程师类型">
          <el-select  v-model="queryParams.category" placeholder="工程师类型" clearable style="width: 200px">
            <el-option value="without" label="外部" />
            <el-option value="employment" label="自聘" />
            <el-option value="notemployment" label="非自聘" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="createTime">
          <el-date-picker
            v-model="createTime"
            type="datetimerange"
            format="YYYY-MM-DD"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <el-button
        :icon="Download"
        style="margin-bottom: 12px"
        @click="handleExport"
        >导出</el-button
      >
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="withdrawalList"
        highlight-current-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名称" prop="engineerName" min-width="150">
          <template #default="scope">
            <span @click="openDialog(scope.row.id)" style="cursor: pointer;color: #409eff">{{
              scope.row.engineerName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户类型" prop="category" min-width="150">
          <template #default="scope">
            <p v-if="scope.row.category === 'without'">外部</p>
            <p v-if="scope.row.category === 'employment'">自聘</p>
            <p v-if="scope.row.category === 'notemployment'">非自聘</p>
          </template>
        </el-table-column>
        <el-table-column label="银行卡号" prop="cardNo" min-width="150" />
        <el-table-column label="开户行" prop="cardAddress" min-width="150" />
        <el-table-column label="开户名" prop="cardName" min-width="150" />
        <el-table-column label="提现金额" prop="money" width="160">
        </el-table-column>
        <el-table-column label="申请时间" prop="createTime" width="190" />
        <el-table-column label="打款时间" prop="updateTime" width="190">
          <template #default="scope">
            <p>{{scope.row.updateTime ? scope.row.updateTime : "/" }}</p>
          </template>
        </el-table-column>
        <el-table-column label="是否审核" prop="isCheckName" width="190" />
        <el-table-column label="失败原因" prop="remark" width="190" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="success"
              link
              @click.stop="getEngineerOrderList(scope.row)"
            >
              查看订单列表
            </el-button>
            <el-button
              type="success"
              v-if="scope.row.isCheck === 0"
              link
              @click.stop="approval(scope.row)"
            >
              打款成功
            </el-button>
            <el-button
              type="success"
              v-if="scope.row.isCheck === 0"
              link
              @click.stop="turnDown(scope.row)"
            >
              打款失败
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="dialogFormVisible" title="失败原因" width="30%">
        <el-form>
          <el-form-item label="原因">
            <el-input
              v-model="remark"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="bohui">
              {{ bottomName }}
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- pagination -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 用户提现详情 -->
    <el-dialog
      title="提现详情"
      v-model="dialog.visible"
      width="600px"
      append-to-body
      @close="closeDialog"
    >
      <el-form label-width="200px" label-position="left">
        <el-form-item label="累计提现金额：">{{
          formData.cumulativeAmount
        }}</el-form-item>
        <el-form-item label="总收入金额：">{{
          formData.totalAmount
        }}</el-form-item>
        <el-form-item label="已提现金额：">{{
          formData.withdrawnAmount
        }}</el-form-item>
        <el-form-item label="本次提现金额：">{{
          formData.withdrawnAmountOnThis
        }}</el-form-item>
        <el-form-item label="未提现金额：">{{
            formData.withdrawnAmountOnNo
          }}</el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <engineerOrderList ref="engineerOrderListRef"></engineerOrderList>
  </div>
</template>
